//
//  TWAuthorViewController.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/4/12.
//  Copyright © 2017年 个人. All rights reserved.
//  单独写

import UIKit
import SnapKit
import MJRefresh
import SVProgressHUD

let FromAuthorVc = "FromAuthorVc"


class TWAuthorViewController: UIViewController {

    fileprivate lazy var tableView : UITableView = UITableView()
    fileprivate lazy var nextPageUrl : String = String()
    fileprivate lazy var footerNullView : UILabel = UILabel()                               // 空的脚部视图
    fileprivate lazy var footerView : TWFooterView = TWFooterView.createFooterView()        // 脚部视图
    fileprivate lazy var authorDataArray : NSMutableArray = NSMutableArray()
    var isFooterRefreshing :Bool = false                                                    // 正在上拉加载更多
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupNullFooter()
        setupTableView()
        setupNav()
        setupRefresh()
        setupNotifications()
    }
}

// MARK:- 通知
extension TWAuthorViewController {
    fileprivate func setupNotifications(){
        NotificationCenter.default.addObserver(self, selector: #selector(detailCollectionViewCellDidClick(note:)), name: NSNotification.Name(rawValue: DetailCollectionViewCellDidClickNotification), object: nil)
    }
    @objc fileprivate func detailCollectionViewCellDidClick(note : NSNotification){
        let dict = note.object as! [String : AnyObject]
        if dict.keys.first == FromAuthorVc {
            let selectModel = dict.values.first as! TWItemModel // 拿到当前选中的模型
            let animationViewController : TWAnimationViewController = TWAnimationViewController()
            animationViewController.itemModel = selectModel
            present(animationViewController, animated: true, completion: nil)
        }
    }
}

// MARK:- 请求数据
extension TWAuthorViewController {

    /// 请求最新网络数据
    fileprivate func loadNewAuthorData(urlString : String){
        loadingAuthorData(isLoadNewData: true, urlString: urlString)
    }
    /// 加载更多数据
    fileprivate func loadMoreAuthorData(){
        print(nextPageUrl)
        loadingAuthorData(isLoadNewData: false, urlString: nextPageUrl)
    }
    
    private func loadingAuthorData(isLoadNewData : Bool, urlString : String){
        TWNetworkTool.shareInstance.loadAuthorData(urlString: urlString) { (result, error) in
            if error != nil {
                self.tableView.mj_header.endRefreshing()
                self.footerEndRefresh()
                SVProgressHUD.showError(withStatus: "加载失败！")
            }
            guard let result = result else {
                return
            }
            let next = result["nextPageUrl"]
            if String(describing: next!) == "<null>" {
                self.footerEndRefresh()
                self.tableView.tableFooterView = self.footerNullView
                return
            } else {
                self.nextPageUrl = next as! String
            }
            // 处理cell相关的数据
            self.dealWithData(isLoadNewData : isLoadNewData, result: result)
        }
    }
    private func dealWithData(isLoadNewData : Bool, result : [String : AnyObject]){
        // 需要展示主体数据的数组
        let itemListArray = result["itemList"] as! [[String : AnyObject]]
        let tempArray : NSMutableArray = NSMutableArray()
        // 遍历数组,判断是什么类型，转成模型
        for item in itemListArray {
            let dataType = item["type"] as! String
            if dataType == TextCard {
                // 相当于标题
                let itemModel : TWTextCardModel = TWTextCardModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([TextCard : itemModel])
            } else if dataType == BriefCard {
                // 相当于系统的cell样式
                let itemModel : TWBriefCardModel = TWBriefCardModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([BriefCard : itemModel])
            } else if dataType == BlankCard {
                // 一个间隙大小
                let itemModel : TWBlankCardModel = TWBlankCardModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([BlankCard : itemModel])
            } else if dataType == VideoCollectionWithBrief {
                let itemModel : TWVideoCollectionOfAuthorWithCoverModel = TWVideoCollectionOfAuthorWithCoverModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([VideoCollectionWithBrief : itemModel])
            } else {
                TWLog(message: "其他未知类型的数据")
            }
        }
        
        if isLoadNewData {
            authorDataArray.removeAllObjects()
            for item in tempArray {
                authorDataArray.add(item)
            }
        } else {
            for item in tempArray {
                authorDataArray.add(item)
            }
        }

        // 刷新UI
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            self.tableView.reloadData()
            self.tableView.tableFooterView = self.footerView
            self.tableView.mj_header.endRefreshing()
            self.footerEndRefresh()
            SVProgressHUD.dismiss()
        }
    }
}

// MARK:- 搭建UI界面
extension TWAuthorViewController {
    fileprivate func setupNav(){
        let navView = UIView(frame: CGRect(x: 0, y: 0, width: TWScreenWidth, height: NavigationBarHeight))
        navView.backgroundColor = UIColor(red: 249 / 255.0, green: 249 / 255.0, blue: 249 / 255.0, alpha: 1.0)
        self.view.addSubview(navView)
        
        let dismissButton = UIButton(type: .custom)
        dismissButton.setImage(UIImage(named: "Action_close_44x44_"), for: .normal)
        dismissButton.addTarget(self, action: #selector(dismissButtonClick), for: .touchUpInside)
        navView.addSubview(dismissButton)
        dismissButton.snp.makeConstraints { (make) in
            make.left.bottom.equalTo(navView)
            make.height.width.equalTo(44)
        }
        
        let titleLabel = UILabel()
        titleLabel.text = "全部作者"
        titleLabel.font = UIFont.init(name: "FZLTZCHJW--GB1-0", size: 18)
        titleLabel.sizeToFit()
        navView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(navView)
            make.centerY.equalTo(dismissButton)
        }
        
        let lineLabel = UILabel()
        lineLabel.backgroundColor = UIColor(red: 201 / 255.0, green: 201 / 255.0, blue: 201 / 255.0, alpha: 0.5)
        navView.addSubview(lineLabel)
        lineLabel.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(navView)
            make.height.equalTo(0.5)
        }
    }
    fileprivate func setupTableView(){
        tableView.frame = CGRect(x: 0, y: 0, width: TWScreenWidth, height: TWScreenHeight)
        tableView.contentInset = UIEdgeInsets(top: NavigationBarHeight, left: 0, bottom: 0, right: 0)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.register(UINib(nibName: "TWVideoCollectionWithBrief", bundle: nil), forCellReuseIdentifier: VideoCollectionWithBrief)
        tableView.register(UINib(nibName: "TWBriefCardCell", bundle: nil), forCellReuseIdentifier: BriefCardCell)
        tableView.register(UINib(nibName: "TWTextCardCell", bundle: nil), forCellReuseIdentifier: TextCardCell)
        tableView.register(UINib(nibName: "TWBlankCardCell", bundle: nil), forCellReuseIdentifier: BlankCardCell)
        view.addSubview(tableView)
    }
    fileprivate func setupRefresh(){
        tableView.mj_header = TWRefreshHeader(refreshingTarget: self, refreshingAction: #selector(refreshLoadNewData))
        tableView.mj_header.beginRefreshing()
    }
    fileprivate func setupNullFooter(){
        // 没有数据时的tableFooterView
        footerNullView = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100))
        footerNullView.text = "-end-"
        footerNullView.font = UIFont.init(name: "Lobster1.4", size: 15)
        footerNullView.textAlignment = .center
    }
}

// MARK:- 监听点击
extension TWAuthorViewController {
    @objc fileprivate func dismissButtonClick(){
        dismiss(animated: true, completion: nil)
    }
    @objc fileprivate func refreshLoadNewData(){
        loadNewAuthorData(urlString: AuthorUrlString)
    }
    @objc fileprivate func refreshLoadMoreData(){
        loadMoreAuthorData()
    }
}

// MARK:- UITableViewDataSource代理方法
extension TWAuthorViewController : UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        self.tableView.tableFooterView?.isHidden = authorDataArray.count == 0 ? true : false
        return authorDataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 取出当前对应的类型
        let data = authorDataArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        // 根据类型展示cell
        switch key {
        case TextCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: TextCardCell, for: indexPath) as! TWTextCardCell
            cell.selectionStyle = .none
            let model = data.values.first as! TWTextCardModel
            cell.model = model
            return cell
        case BriefCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: BriefCardCell, for: indexPath) as! TWBriefCardCell
            cell.selectionStyle = .none
            let model = data.values.first as! TWBriefCardModel
            cell.model = model
            return cell
        case BlankCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: BlankCardCell, for: indexPath) as! TWBlankCardCell
            cell.selectionStyle = .none
            return cell
        case VideoCollectionWithBrief:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCollectionWithBrief, for: indexPath) as! TWVideoCollectionWithBrief
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWVideoCollectionOfAuthorWithCoverModel
            cell.model = itemCollectionModel
            cell.bottomCollectionView.fromWhichVc = FromAuthorVc
            cell.videoCollectionWithBriefDelegate = self
            return cell
        default:
            return UITableViewCell()
        }
    }
}

// MARK:- VideoCollectionWithBriefDelegate的代理方法
extension TWAuthorViewController : VideoCollectionWithBriefDelegate {
    func pushViewControllerWith(model: TWVideoCollectionOfAuthorWithCoverModel) {
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.yellow
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK:- UITableViewDelegate代理方法
extension TWAuthorViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        // 取出当前对应的类型
        let data = authorDataArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        // 根据类型展示cell
        if key == TextCard {
            return TextCardHeight
        } else if key == BriefCard {
            return BriefCardHeight
        } else if key == BlankCard {
            return BlankCardHeight
        } else if key == VideoCollectionWithBrief {
            return videoCollectionWithBriefCellHeight
        } else {
            return 0
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 取出当前对应的类型
        let data = authorDataArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        // 根据类型展示cell
        if key == BriefCard {
//            let model = data.values.first as! TWBriefCardModel
//            let vc = UIViewController()
//            vc.view.backgroundColor = UIColor.yellow
////            self.navigationController?.pushViewController(vc, animated: true)
//            lastVc?.navigationController?.pushViewController(vc, animated: true)
        }
    }
}

// MARK:- 代理方法
extension TWAuthorViewController {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let insetTop = NavigationBarHeight
        // 滚动偏移量
        let offset = -(tableView.contentOffset.y + insetTop)  // 默认为0
        dealFooter(offset: offset)
    }
    fileprivate func dealFooter(offset : CGFloat){
        // 还没有任何内容的时候，不需要判断
        if tableView.contentSize.height == 0 {
            return
        }
        if isFooterRefreshing {
            return
        }
        // 计算偏移量 = 内容的顶部和frame的顶部的差值,tableView.contentSize包括header和footer
        let ofsetY = tableView.contentSize.height + tableView.contentInset.bottom - tableView.frame.height
        if tableView.contentOffset.y >= ofsetY && self.tableView.contentOffset.y > -(self.tableView.contentInset.top) {
            footerBeginRefresh()
        }
    }
    // MARK:- 刷新相关
    func footerBeginRefresh() {
        if isFooterRefreshing {
            return
        }
        // 进入刷新状态
        isFooterRefreshing = true
        footerView.addRotationAnimation()
        loadMoreAuthorData()
    }
    func footerEndRefresh() {
        isFooterRefreshing = false
        footerView.loading_in_ImageView.layer.removeAllAnimations()
    }
}


